<?php

use App\Logic\JwtLogic;
use App\Model\SyncErrorLogModel;
use App\Model\SystemConfigModel;
use App\Service\SnowflakeIdGenerator;
use Hyperf\Cache\Cache;
use Hyperf\Context\ApplicationContext;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\HttpMessage\Server\Response;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Redis\Redis;
use App\RpcConsumer\SystemConfigServiceInterface;
use Hyperf\Context\Context;

use function Hyperf\Support\env;
use function Hyperf\Support\make;

if (!function_exists("sendHttpPost")) {
    /**
     * http Post 请求
     * @param $url string url
     * @param $data array 参数
     * @param $header array headers
     * @retrun  list(bool $a, interface $b)
     */
    function sendHttpPost($url, $data, $header = []): array
    {
        try {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            if ($header) {
                curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
            }
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, False);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($curl, CURLOPT_HEADER, FALSE);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $retdata = curl_exec($curl);
            $error = curl_error($curl);
            if ($error) {
                return [false, $error];
            }
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            if ($httpCode != 200) {
                return [false, $httpCode];
            }
            writeLog("curl_error返回值" . $error, 'info', 'info');
            curl_close($curl);
            return [true, $retdata];
        } catch (Throwable $e) {
            return [false, $e->getMessage()];
        }
    }
}

if (!function_exists("sendHttpGet")) {
    function sendHttpGet($url, $data, $headers = [])
    {
        try {
            if (strpos("?", $url) === false) {
                $url = $url . "?" . http_build_query($data);
            } else {
                $url = $url . "&" . http_build_query($data);
            }
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($curl, CURLOPT_FAILONERROR, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            if (1 == strpos("$" . $url, "https://")) {
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            }
            $retdata = curl_exec($curl);
            curl_close($curl);
            return [true, $retdata];
        } catch (Throwable $e) {
            return [false, $e->getMessage()];
        }
    }
}

if (!function_exists("createPassword")) {
    /**
     * 生成密码密文
     * @param $password string
     * @param $salt string
     * @return string
     */
    function createPassword(string $password, string $salt): string
    {
        return md5(md5($password) . $salt);
    }
}

if (!function_exists('request')) {
    /**
     * @Description: 获取请求对象
     * @Author: maojian
     */
    function request()
    {
        return ApplicationContext::getContainer()->get(RequestInterface::class);
    }
}

if (!function_exists('response')) {
    /**
     * @Description: 获取响应对象
     * @Author: maojian
     */
    function response()
    {
        return ApplicationContext::getContainer()->get(ResponseInterface::class);
    }
}

if (!function_exists("retJson")) {
    /**
     * @Description: 返回结果助手函数
     * @Author: maojian
     * @param {*} $code
     * @param {*} $msg
     * @param {*} $data
     */
    function retJson($code = 200, $msg = "", $data = [])
    {
        return response()->json(["code" => $code, "msg" => $msg, "data" => $data], JSON_UNESCAPED_UNICODE);
    }
}


if (!function_exists("input")) {
    /**
     * @Description:  获取请求参数
     * @Author: maojian
     * @param {string} $column
     * @param {*} $default
     */
    function input(string $column, $default = "")
    {
        return request()->input($column, $default);
    }
}

if (!function_exists("validatePhone")) {
    /**
     * @Description:  验证手机号
     * @Author: liyang
     * @param {int} $phone
     */
    function validatePhone($phone)
    {
        $pattern = '/^[1][3-9]+\\d{9}$/';
        if (preg_match($pattern, $phone)) {
            return true; // 手机号符合规则
        } else {
            return false; //手机号不符合规则
        }
    }
}

if (!function_exists("validatePassword")) {
    /**
     * @Description:  验证登录密码
     * @Author: liyang
     * @param {int} $password
     */
    function validatePassword($password)
    {
        // 正则表达式：密码由字母和数字组成，且长度不低于6位
        $pattern = '/^[a-zA-Z0-9]{6,}$/';
        // 使用preg_match()函数进行匹配
        if (preg_match($pattern, $password)) {
            return true; // 密码符合规则
        } else {
            return false; // 密码不符合规则
        }
    }
}

if (!function_exists("cdnHost")) {
    /**
     * @Description: Cdn 域名
     * @Author: maojian
     * @param {*} $path
     */
    function cdnHost($path)
    {
        return env("APP_CDN_HOST", "") . $path;
    }
}

if (!function_exists("appHost")) {
    /**
     * @Description: Cdn 域名
     * @Author: maojian
     * @param {*} $path
     */
    function appHost($param)
    {
        return env("APP_HOST", "") . $param;
    }
}

if (!function_exists("fileHost")) {
    /**
     * @Description: Cdn 域名
     * @Author: xuzya
     * @param {*} $file
     */
    function fileHost($file, $returnArr = false)
    {
        $imgs = [];
        $img = '';
        if (!empty($file)) {
            $str = strpos($file, ',');
            if ($str) {
                $images = explode(",", $file);
                foreach ($images as $val) {
                    $imgs[] = !empty($val) ? cdnHost($val) : '';
                }
            } else {
                $img = cdnHost($file);
                if ($returnArr) {
                    array_push($imgs, $img);
                }
            }
        }
        return !empty($imgs) ? $imgs : $img;
    }
}


if (!function_exists("getUserId")) {
    /**
     * @Description: 获取用户ID
     * @Author: maojian
     */
    function getUserId()
    {
        return 522;
        $uid = request()->getHeaderLine("hyperf_jwt_uid");
        if (!$uid) {
            throw new Exception("Uid Not Found !");
        }
        return $uid;
    }
}
if (!function_exists("touristAndUser")) {
    /**
     * @Description: 游客和用户混合模式
     * @Author:allen
     * @date:2024/03/11
     */
    function touristAndUser()
    {
        // $token = request()->getHeaderLine("token");
        // $jwtLogic = make(JwtLogic::class);
        // if (empty($token)) {
        //     return 0;
        // }
        // list($status, $param) = $jwtLogic->jwtParse($token);
        // if ($param) {
        //     return $param->get("uid");
        // } else {
        //     // throw new Exception("Uid Not Found !");
        //     return 0;
        // }
        return 0;
    }
}
if (!function_exists("createOrderNo")) {
    /**
     * @Description: 创建订单号
     * @Author: maojian
     * @param {*} $head 订单前戳
     */
    function createOrderNo($head = "")
    {
        $date = date("ymdHis");
        $cacheKey = "order_no_uniqid:{$date}";
        $cache = getRedis();
        $num = $cache->incr($cacheKey);
        $cache->expire($cacheKey, 60);
        $num = sprintf("%04d", $num) + mt_rand(1000, 9999);
        $orderNo = $head . $date . $num;
        return $orderNo;
    }
}


if (!function_exists("getRedis")) {
    /**
     * @Description: 获取redis实例
     * @Author: maojian
     */
    function getRedis()
    {
        return ApplicationContext::getContainer()->get(Redis::class);
    }
}
if (!function_exists("generateRandomString")) {
    /**
     * @Description: 生成随机字符串
     * @Author: maojian
     * @param {*} $length
     */
    function generateRandomString($length = 10, $excludeStr = [])
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

        if (!empty($excludeStr)) {
            foreach ($excludeStr as $value) {
                $characters = str_replace($value, '', $characters);
            }
        }
        $string = '';
        for ($i = 0; $i < $length; $i++) {
            $string .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $string;
        // return substr(sha1($string), 0, $length);
    }
}

if (!function_exists("checkConsecutiveChanges")) {
    // 判断是否连续增加或减少
    function checkConsecutiveChanges($data, $isIncreasing = true)
    {
        $count = count($data);
        if ($count < 2) {
            return false; // 数据不足以判断
        }

        for ($i = 0; $i < $count - 1; $i++) {
            $current = $data[$i];
            $next = $data[$i + 1];

            if (($isIncreasing && $current >= $next) || (!$isIncreasing && $current <= $next)) {
                return false; // 发现不连续的情况
            }
        }

        return true; // 所有数据都连续增加或减少
    }
}

if (!function_exists("randomFloat")) {
    //两个浮点型取随机数
    function randomFloat($min, $max)
    {
        $number = $min + mt_rand() / mt_getrandmax() * ($max - $min);
        return number_format($number, 2);
    }
}

if (!function_exists("writeLog")) {
    /**
     * @Description: 记录日志
     * @Author: maojian
     * @param $data 日志内容 string|int|array|object
     * @param $level 日志级别 debug|info|warnning|error
     * @param $channal 日志通道 /config/autoload/logger 自定义 默认 default
     */
    function writeLog($data, $level = "debug", $channal = "default")
    {
        // ApplicationContext::getContainer()->get(StdoutLoggerInterface::class)->debug(is_string($data) ? $data : serialize($data));
        $logs = ApplicationContext::getContainer()->get(LoggerFactory::class)->get($level, $channal);
        return $logs->$level(is_string($data) ? $data : serialize($data));
    }
}

if (!function_exists("chanceLottery")) {
    /**
     * @Description: 盲盒概率随机
     * @Author: liyang
     * @param $box_id array 中奖id
     * @param $prizes array 中奖名称
     * @param $probabilities array 概率
     */
    function chanceLottery($box_id, $prizes, $probabilities)
    {
        $totalProbability = array_sum($probabilities); //计算总概率
        $randomNumber = mt_rand(1, $totalProbability); // 生成一个随机数
        $probabilitySum = 0; //当前累计概率
        for ($i = 0; $i < count($prizes); $i++) {
            $probabilitySum += $probabilities[$i];
            if ($probabilitySum >= $randomNumber) {
                return array(
                    'box_id' => $box_id[$i],
                    'chance' => $probabilities[$i],
                    'box_name' => $prizes[$i]
                );
            }
        }
    }
}

if (!function_exists("ActivityChanceLottery")) {
    /**
     * @Description: 活动概率随机
     * @Author: liyang
     * @param $lottery_id array 中奖id
     * @param $lottery_name array 中奖名称
     * @param $lottery_chance array 中奖概率
     */
    function ActivityChanceLottery($lottery_id, $lottery_name, $lottery_chance)
    {
        $totalProbability = array_sum($lottery_chance); //计算总概率
        $randomNumber = mt_rand(1, $totalProbability); // 生成一个随机数
        $probabilitySum = 0; //当前累计概率
        for ($i = 0; $i < count($lottery_name); $i++) {
            $probabilitySum += $lottery_chance[$i];
            if ($probabilitySum >= $randomNumber) {
                return array(
                    'lottery_id' => $lottery_id[$i],
                    'lottery_chance' => $lottery_chance[$i],
                    'lottery_name' => $lottery_name[$i]
                );
            }
        }
    }
}
if (!function_exists("createNickname")) {
    /**
     * @Description: 创建随机用户名
     * @Author: liyang
     * @param $prefix string 前缀
     */
    function createNickname($prefix)
    {
        $characters = '012356789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $string = '';
        for ($i = 0; $i < 6; $i++) {
            $string .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $prefix . substr($string, 0, 6);
        // $nickname = $prefix . mt_rand(100000, 999999);
        // return $nickname;
    }
}

if (!function_exists("hideNickname")) {
    /**
     * @Description: 隐藏用户名
     * @param $prefix string 前缀
     */
    function hideNickname($nickname)
    {
        $len = mb_strlen($nickname);
        if ($len >= 6) {
            $nickname = mb_substr($nickname, 0, 2) . '****' . mb_substr($nickname, -2);
        } elseif ($len > 2 && $len < 6) {
            $sign = '';
            for ($i = 1; $i <= $len - 2; $i++) {
                $sign .= '*';
            }
            $nickname = mb_substr($nickname, 0, 1) . $sign . mb_substr($nickname, -1);
        } else {
            $nickname = mb_substr($nickname, 0, 1) . '*';
        }

        return $nickname;
    }
}


/**
 * @Description: 请求ip
 * @Author: maojian
 */
if (!function_exists('realIp')) {
    function realIp()
    {
        $x_real_ip = request()->getHeaderLine("x-real-ip");
        if ($x_real_ip) {
            return $x_real_ip;
        }
        $x_forwarded_for = request()->getHeaderLine("x-forwarded-for");
        if ($x_forwarded_for) {
            return $x_forwarded_for;
        }
        $serverParam = request()->getServerParams();
        if (isset($serverParam["remote_addr"])) {
            return $serverParam["remote_addr"];
        }
        return '';
    }
}
/**
 * @Description: 设备场景
 * @Author: maojian
 */
if (function_exists('deviceInfo')) {
    function deviceInfo()
    {
        $userAgent = request()->getHeaderLine("User-Agent");
        $platform = 'h5';
        $a_strtolower = strtolower($userAgent);
        if (strpos($a_strtolower, "micromessenger")) //公众号MicroMessenger
        {
            if (strpos($a_strtolower, "miniprogram")) //小程序
            {
                $platform = 'weapp';
            } else
                $platform = 'h5';
        } elseif (strpos($a_strtolower, "uni-app") || strpos($a_strtolower, "Html5Plus")) //app
        {
            $platform = 'app';
        }
        return $platform;
    }
}

if (!function_exists('getDomain')) {
    function getDomain()
    {
        $requestUri = request()->getUri();
        $domain = "https://" . $requestUri->getHost();
        return $domain;
    }
}

// /**
//  * @Description: 读取系统配置
//  * @group {string} 分组
//  * @column {string} 组内参数值
//  * @Author: maojian
//  */
// if (!function_exists('getSysConfig')) {
//     function getSysConfig($group, $column = '', $default = '')
//     {
//         $model = make(SystemConfigModel::class);
//         if ($column) {
//             list($null, $data) = $model->getColumn($group, $column);
//         } else {
//             list($null, $data) = $model->getGroup($group);
//         }
//         return $data ?? $default;
//     }
// }

/**
 * @Description: 读取系统配置
 * @group {string} 分组
 * @column {string} 组内参数值
 * @Author: maojian
 */
if (!function_exists('getSysConfig')) {
    function getSysConfig($group, $column = '', $default = '')
    {
        try {
            $rpcCalculator = ApplicationContext::getContainer()->get(SystemConfigServiceInterface::class);
            $data = $rpcCalculator->getSysConfig($group, $column);
            return $data ?? $default;
        } catch (\Exception $e) {
            writeLog("Failed to get config by group: " . $group . ". Error: " . $e->getMessage());
            return $default;
        }
    }
}

/**
 * @Description: 读取系统配置
 * @group {string} 分组
 * @column {string} 组内参数值
 * @Author: maojian
 */
if (!function_exists('getConfigByName')) {
    function getConfigByName($name, $default = '')
    {
        try {
            $rpcCalculator = ApplicationContext::getContainer()->get(SystemConfigServiceInterface::class);
            $data = $rpcCalculator->getConfigByName($name);
            return $data ?? $default;
        } catch (\Exception $e) {
            writeLog("Failed to get config by name: " . $name . ". Error: " . $e->getMessage());
            return $default;
        }
    }
}

if (!function_exists("snowflakeIdGenerator")) {
    /**
     * 生成雪花id
     * @Author: zsj
     */
    function snowflakeIdGenerator($id = 1)
    {
        $generator = new SnowflakeIdGenerator($id);
        return $generator->generate();
    }
}

/**
 * @Description: 手机号码脱敏
 * @Author: xuzya
 * @param {*} $phone
 * @return {*}
 */
if (!function_exists('maskPhoneNumber')) {
    function maskPhoneNumber($phoneNumber)
    {
        // 替换中间4位为星号
        $maskedNumber = substr_replace($phoneNumber, '****', 3, 4);

        return $maskedNumber;
    }
}
/**
 * @Description: 手机号码脱敏6位*
 * @Author: zsj666
 * @param {*} $phone
 * @return {*}
 */
if (!function_exists('maskPhoneSexNumber')) {
    function maskPhoneSexNumber($phoneNumber)
    {
        // 替换中间4位为星号
        $maskedNumber = substr_replace($phoneNumber, '******', 3, -2);

        return $maskedNumber;
    }
}


/**
 * @Description: 订单号脱敏
 * @Author: zsj666
 * @param {*} $phone
 * @return {*}
 */
if (!function_exists('maskOrderNoNumber')) {
    function maskOrderNoNumber($orderNo)
    {
        // 替换中间4位为星号
        $maskedNumber = substr_replace($orderNo, '******', 3, -6);

        return $maskedNumber;
    }
}

/**
 * 根据指定字符生成指定位数随机字符串
 * xuzya
 * @param {string} $characters 指定字符
 * @param {int} $length 生成长度
 */
if (!function_exists('generateSpecificDigitString')) {
    function generateSpecificDigitString($characters, $length)
    {
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomIndex = rand(0, $charactersLength - 1);
            $randomChar = $characters[$randomIndex];
            $randomString .= $randomChar;
        }
        return $randomString;
    }
}

/**
 *  * 过滤html，p标签过滤为换行
 *  */
if (!function_exists('filterHtml')) {
    function filterHtml($html)
    {
        $text = strip_tags($html, ['<p>', '</p>', '<br/>', '<br>']);
        $text = str_replace("&nbsp;", " ", $text);
        $text = str_replace("<p>", "\n", $text);
        $text = str_replace("</p>", "", $text);
        $text = str_replace("<br/>", "", $text);
        $text = str_replace("<br>", "\n", $text);

        $text = trim($text);

        return $text;
    }
}

function dev_log($key = null, $val = null)
{
    $data = (array)Context::get('dev_log');
    if ($key) {
        if (!is_string($key)) {
            $tmp = $key;
            $key = date('H:i:s' . mt_rand(100000, 999999));
            $val = $val === null ? $tmp : func_get_args();
        }
        $data[] = [$key, $val];
        Context::set('dev_log', $data);
    }
    return $data;
}
